package top.csy8888.likework.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.csy8888.likework.common.confirm.ConfirmCallbackService;
import top.csy8888.likework.common.consts.RedisKeyEnum;
import top.csy8888.likework.dto.LikeDTO;

import java.io.IOException;

/**
 * @author CSY
 * @date 2025 - 10 - 15
 * 当点赞信息投递失败时，执行这个CallbackService
 */
@Service
@RequiredArgsConstructor
public class LikeConfirmCallback implements ConfirmCallbackService {
    /**
     * 注入RedisTemplate
     */
    private final RedisTemplate<String, Integer> redisTemplate;
    /**
     * 执行失败后的方向操作
     * @param message 投递的消息对象
     */
    @Override
    public void confirmCallback(Message message) {
        byte[] bytes = message.getBody();
        try {
            //反序列化为likeDTO对象
            LikeDTO dto = new ObjectMapper().readValue(bytes,LikeDTO.class);
            if (dto.getLikeStatus()){
                redisTemplate.opsForSet().remove(RedisKeyEnum.POST_LIKE_PREFIX.value()+dto.getPostId(),dto.getUserId());
            }else{
                redisTemplate.opsForSet().add(RedisKeyEnum.POST_LIKE_PREFIX.value()+dto.getPostId(),dto.getUserId());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
